#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import re
import shutil
import pathlib
from bidict import bidict
from ...._util import Util, CopiedAndSymlinkedDir
from ...._errors import ConfigError
from ...._game import GameBase, GameSpec, MatchContext
from ...._game_straits import GameStraitForWindows, GameStraitNeedConfigDir


class Limbo(GameBase, GameStraitForWindows):

    def __init__(self, data_dir):
        GameBase.__init__(self, data_dir)

        self._addStrait(GameStraitNeedConfigDir())

        self._spec = GameSpec()
        if True:
            self._spec.windows_archs = [self.WindowsArch.WIN32]
            self._spec.windows_versions = [self.WindowsVersion.WINXP, "*"]

            self._spec.default_language = _SettingsFile.defaultLang
            self._spec.languages = list(_SettingsFile.langDict.keys())

            self._spec.resolutions = ["*"]
            self._spec.can_fullscreen = True
            self._spec.can_windowed = False

    @property
    def spec(self):
        return self._spec

    @property
    def run_items(self):
        return ["main"]

    def get_title(self, lang):
        return "LIMBO"

    def _prepare(self, context):
        self._context = context
        try:
            self._targetGameDirObj = CopiedAndSymlinkedDir(os.path.join(self._context.drive_c_dirpath, "game"), [self._dataDir])
            for fn in os.listdir(self._dataDir):
                if fn == _SettingsFile.filename:
                    if not self._targetGameDirObj.exists(fn):
                        self._targetGameDirObj.copy(fn)
                else:
                    self._targetGameDirObj.symlink(fn, recursive=True)

            self._cfgFile = _SettingsFile(self._targetGameDirObj.path)

            self._profileRepo = _ProfileRepository(self._targetGameDirObj.path, self._context.config_dirpath)
            self._profileRepo.restore_current()
        except BaseException:
            self._cleanup(on_error=True)
            raise

    @MatchContext.edit_or_run
    def get_language(self):
        return self._cfgFile.language

    @MatchContext.edit_or_run
    def set_language(self, language):
        self._cfgFile.language = language

    @MatchContext.edit
    def list_backup_profiles(self):
        return self._profileRepo.list_backups()

    @MatchContext.edit
    def save_backup_profile(self, name):
        assert name is not None
        self._profileRepo.backup_current(name)

    @MatchContext.edit
    def remove_backup_profile(self, name):
        assert name is not None
        self._profileRepo.remove_backup(name)

    @MatchContext.edit
    def use_backup_profile(self, name):
        assert name is not None
        self._profileRepo.restore_current(name)

    @MatchContext.edit
    def use_perfect_profile(self):
        self._profileRepo.use_perfect_profile_as_current()

    @MatchContext.edit
    def reset_profile(self):
        self._profileRepo.remove_current()

    @MatchContext.run
    def apply_resolution(self, resolution):
        pass

    @MatchContext.run
    def apply_fullscreen_or_windowed(self, fullscreen_or_windowed):
        assert fullscreen_or_windowed

    def _commit(self):
        self._cfgFile.save()

    def _getRunInfo(self, item):
        assert not self._context.edit_or_run
        assert item == Util.listGetOnlyItem(self.run_items)

        # Crash if cwd is not specified
        return self.RunInfo("C:\\game\\limbo.exe", cwd="C:\\game")

    def _cleanup(self, on_error=False):
        if not on_error:
            self._profileRepo.backup_current()

        if hasattr(self, "_targetGameDirObj"):
            del self._targetGameDirObj
        if hasattr(self, "_context"):
            del self._context

        return []


class _SettingsFile:

    filename = "settings.txt"

    langDict = bidict({
        "en_US": "uk",
        "ja_JP": "ja",
        "de_DE": "de",
        "fr_FR": "fr",
        "es_ES": "es",
        "it_IT": "it",
        "ko_KR": "ko",
        "zh_CN": "zh",
        "zh_TW": "sz",
        "pt_PT": "pt",
        "ru_RU": "ru",
        "pl_PL": "pl",
        "br_BR": "br",
        "tr_TR": "tr",
    })

    defaultLang = "en_US"

    def __init__(self, game_dir):
        self._path = os.path.join(game_dir, self.filename)
        self._buf = pathlib.Path(self._path).read_text()

        self._lang = None
        if True:
            m = re.search(r'^language = "(\S+)"$', self._buf, re.MULTILINE)
            if m is None:
                raise ConfigError("invalid config file %s" % (self._path))

            self._lang = self.langDict.inverse.get(m.group(1), None)
            if self._lang is None:
                raise ConfigError("invalid config file %s" % (self._path))

    @property
    def language(self):
        return self._lang

    @language.setter
    def language(self, language):
        self._buf.replace('language = "%s"' % (self._lang), 'language = "%s"' % (self.langDict[language]))
        self._lang = language

    def save(self):
        pathlib.Path(self._path).write_text(self._buf)


class _ProfileRepository:

    def __init__(self, game_dir, backup_dir):
        self._tDir = os.path.join(game_dir, "save_game")
        self._tPath = os.path.join(self._tDir, "savegame.txt")
        self._backupDir = backup_dir

    def list_backups(self):
        ret = []
        for fn in os.listdir(self._backupDir):
            if fn == "savegame.txt":
                continue
            if not fn.endswith(".txt"):
                continue
            ret.append(fn)
        return ret

    def remove_current(self):
        Util.forceDelete(self._tDir)
        Util.forceDelete(os.path.join(self._backupDir, "savegame.txt"))

    def remove_backup(self, name):
        assert name is not None
        Util.forceDelete(os.path.join(self._backupDir, self._name2fn(name)))

    def backup_current(self, name=None):
        bakFile = os.path.join(self._backupDir, self._name2fn(name))
        if os.path.exists(self._tPath):
            shutil.copy(self._tPath, bakFile)
        else:
            Util.forceDelete(bakFile)

    def restore_current(self, name=None):
        bakFile = os.path.join(self._backupDir, self._name2fn(name))
        if os.path.exists(bakFile):
            os.makedirs(self._tDir, exist_ok=True)
            shutil.copy(bakFile, self._tPath)
        else:
            Util.forceDelete(self._tDir)

    def use_perfect_profile_as_current(self):
        # FIXME: it seems different version has different savegame file format
        selfDir = os.path.dirname(os.path.realpath(__file__))
        os.makedirs(self._tDir, exist_ok=True)
        shutil.copy(os.path.join(selfDir, "savegame.txt"), self._tPath)

    @staticmethod
    def _name2fn(name):
        if name is None:
            return "savegame.txt"
        else:
            if name == "savegame":
                raise ValueError("invalid profile name")
            return name + ".txt"
